from datetime import datetime
from time import sleep

from appium import webdriver
from appium.webdriver.webdriver import WebDriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.wait import WebDriverWait

from appium_xueqiu.until.until import black_handle
from appium_xueqiu.until.web_until import check_ele


class BasePage:
    BLACK_LIST = [(AppiumBy.ID, "com.xueqiu.android:id/iv_close")]

    _CAPABILITY = {
        "platformName": "Android",
        "platformVersion": "7.1.2",
        "appActivity": ".view.WelcomeActivityAlias",
        "appPackage": "com.xueqiu.android",
        "deviceName": "Nox-5544",
        "noReset": 'true'
    }

    __TV_AGREE = (AppiumBy.ID, "com.xueqiu.android:id/tv_agree")
    __TV_SKIP = (AppiumBy.ID, "com.xueqiu.android:id/tv_skip")
    __FIRST_PAGE = (AppiumBy.ID, "com.xueqiu.android:id/new_user_guide_first_page_item")
    __SKIP_TV = (AppiumBy.ID, "com.xueqiu.android:id/new_user_guide_skip_tv")
    __START_XUEQIU = (AppiumBy.XPATH, "//*[@class='android.widget.TextView' and @text='即刻开启雪球之旅']")

    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    def start_xueqiu(self):
        if not self.driver:
            self.driver = webdriver.Remote("http://localhost:4723/wd/hub", self._CAPABILITY)
            self.driver.implicitly_wait(10)
        else:
            self.driver = self.driver.launch_app()

        # 判断是否welcome页进入雪球
        self.protocol()

        from appium_xueqiu.page_object.main_page import MainPage
        return MainPage(self.driver)

    def protocol(self):
        ele_flag = WebDriverWait(self.driver, 5).until(check_ele(*self.__TV_AGREE))

        if ele_flag != "not ele":
            self.do_click(self.__TV_AGREE)
            self.do_click(self.__FIRST_PAGE)
            self.do_click(self.__SKIP_TV)
            self.do_click(self.__START_XUEQIU)

    @black_handle
    def do_find(self, by, located=None):
        return self.driver.find_element(by, located) if located else self.driver.find_element(*by)

    def do_finds(self, by, located=None):
        return self.driver.find_elements(by, located) if located else self.driver.find_elements(*by)

    def do_click(self, by, located=None):
        ele = self.do_find(by, located)
        ele.click()

        return self

    def do_send_keys(self, msg, by, located=None):
        ele = self.do_find(by, located)
        ele.clear()
        ele.send_keys(msg)

        return self

    def do_select_click(self, select_num, by, located=None):
        eles = self.do_finds(by, located)
        eles[select_num].click()

        return self

    def quit_xueqiu(self):
        self.driver.quit()

    def get_time(self):
        strtime = datetime.now().strftime('%Y-%m-%d_%H_%M_%S')

        return strtime

    def screenshot(self, path):
        self.driver.save_screenshot(path)
